home *** CD-ROM | disk | FTP | other *** search
/ Delphi Magazine Collection 2001 / Delphi Magazine Collection 20001 (2001).iso / DISKS / ISSUE22 / TIPTRIX / LISTING1.PAS next >
Encoding:
Pascal/Delphi Source File  |  1997-05-19  |  2.0 KB  |  86 lines

  1. unit LogStrm;
  2.  
  3. interface
  4.  
  5. uses
  6.   SysUtils, Classes, Forms;
  7.  
  8. type
  9.   TLogFile = class
  10.   private
  11.      logFileName: string;
  12.      stream: TFileStream;
  13.      function GetLogFileName: string;
  14.   public
  15.      constructor Create;
  16.      destructor Destroy;
  17.      procedure WriteToStream(strToWrite: string; blankLine: boolean);
  18.   end;
  19.  
  20. implementation
  21.  
  22. constructor TLogFile.Create;
  23. begin
  24.    logFileName := GetLogFileName;
  25.    stream := TFileStream.Create(logFileName, fmCreate);
  26. end;
  27.  
  28. destructor TLogFile.Destroy;
  29. begin
  30.    stream.Free;
  31. end;
  32.  
  33. procedure TLogFile.WriteToStream(strToWrite: string; blankLine: boolean);
  34. var
  35.    strNew: string;
  36.    lengthStrNew: byte absolute strNew;
  37. begin
  38.    { #13 = carriage return #10 = form feed }
  39.    strNew := Format('%s%s', [strToWrite, #13#10]);
  40.    if blankLine then
  41.       strNew := Format('%s%s', [strNew, #13#10]);
  42.    stream.Write(strNew[1], lengthStrNew);
  43. end;
  44.  
  45. function TLogFile.GetLogFileName: string;
  46. const
  47.    logFileName = 'log';
  48. var
  49.    i: integer;
  50.    logFileNoExt: string;
  51. begin
  52.    logFileNoExt := Concat(ExtractFilePath(Application.ExeName),
  53. logFileName);
  54.    i := 1;
  55.    repeat
  56.       Result := Format('%s%d.txt', [logFileNoExt, i]);
  57.       Inc(i);
  58.    until not FileExists(Result);
  59. end;
  60.  
  61. end.
  62.  
  63. { example ... }
  64. procedure WriteToLogFile;
  65. const
  66.    testDir = 'test';
  67. var
  68.    dirToMake: string;
  69. begin
  70.    with TLogFile.Create do
  71.       try
  72.          WriteToStream(Format('Log begun at %s', [DateTimeToStr(Now)]),True);
  73.          dirToMake := Concat(ExtractFilePath(Application.ExeName), testDir);
  74.          if not DirectoryExists(dirToMake) then begin
  75.             MkDir(dirToMake);
  76.             if IOResult = 0 then
  77.                WriteToStream(Format('Made dir %s', [dirToMake]), False)
  78.             else
  79.                WriteToStream(Format('Unable to make dir %s', [dirToMake]), False);
  80.          end else
  81.             WriteToStream(Format('Directory %s already exists', [dirToMake]), False);
  82.       finally
  83.          Destroy;
  84.       end;
  85. end;
  86.